package npu.dce.andcontact1;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.widget.Toast;

public class UI_DisplayContacts extends Activity{

	private ListView listNames;
	private ContactDBAdapter mDbHelper;
	private ArrayAdapter<String> namePhones;
	private static final int SHOW_SUB_EDIT_ACTIVITY = 1;	
	
	final int CONTEXT_MENU_EDIT_ITEM = 1; 
	final int CONTEXT_MENU_EDLETE_ITEM = 2;
	public static final String DELETE_SUCCESS_MSG = "Delete Successful";
	public static final String DELETE_FAILURE_MSG = "Delete Unsuccessful";
	private static final String contactID = "id";
	
	long contact_id;	
	public String total;
	
	SQLiteDatabase db;
		
	byte[] buf = new byte[1920];
	private Handler mHandler = new Handler(); 
	 
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle bundle) {
		
		//Variable Declaration & Initialization
        this.namePhones = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1);
        
    	super.onCreate(bundle);
    	setContentView(R.layout.displaycontacts);

        this.listNames = (ListView)findViewById(R.id.listNames);
        this.listNames.setAdapter(this.namePhones);
        
        this.mDbHelper = new ContactDBAdapter(UI_DisplayContacts.this);

        //Get all contacts from database
        this.getAllNamePhone();
        
        
        listNames.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	
            	long cont_id = getRowIdFromText(((TextView)view).getText().toString());                          	
            	contactDialog(cont_id);
            	
            }
        });  
        
        UpdatePacket update = new UpdatePacket();
         
    } // OnCreate
	
	private void contactDialog(final long id){
		
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(UI_DisplayContacts.this); 
  	  
        alertDialog.setTitle("Contacts"); 
        alertDialog.setMessage("Please choose edit or delete"); 
 
       
        alertDialog.setPositiveButton("Edit", new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, int which) {              
            	openEditContact_Activity(id);
            } 
        }); 
  
        alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, int which) { 
            	deleteContact(id);
            	clearNamePhone();
            	getAllNamePhone();
            	dialog.cancel();
            	 
            } 
        }); 

        alertDialog.show();
		
	}
	
	private long getRowIdFromText(String text){
		int i = text.indexOf(" ");
		text = text.substring(0, i);
		long id = Long.parseLong(text);
		return id;
	}
	
	private void deleteContact(long id) {
        
		this.mDbHelper.open(); 
        
        boolean status = this.mDbHelper.deleteContact(id);
        
        if(status)
        	this.displayToast(this.DELETE_SUCCESS_MSG);
        else
        	this.displayToast(this.DELETE_FAILURE_MSG);
        
        this.mDbHelper.close();		
	}
	
	private void displayToast(String text){
    	Toast t = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
    	t.show();
    }  
	
	public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_newcontact, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		//Handle Item selected
		switch(item.getItemId()){
		
		case R.id.menu_newcontact:
			this.openNewContact_Activity();			
			return true;
			
		case R.id.menu_revert:
			this.openNewContact_Activity();		
			return true;
			
		default:
			return (super.onOptionsItemSelected(item));//super class returns false		
		}		
	}
    	
	private void openNewContact_Activity(){
		
		Intent intent = new Intent(UI_DisplayContacts.this, Andcontact1.class);
		startActivity(intent);
		
	}

	private void getAllNamePhone(){
        this.mDbHelper.open();               
		
        String id;
		String firstName;
		String familyName;
		String phoneNumber;
		
		Cursor cursor = this.mDbHelper.fetchAllContacts();
		if(cursor.moveToFirst()){
			do{
				id = cursor.getString(cursor.getColumnIndex(ContactDBAdapter.KEY_ROWID));
				firstName = cursor.getString(cursor.getColumnIndex(ContactDBAdapter.KEY_GIVENNAME));
				familyName = cursor.getString(cursor.getColumnIndex(ContactDBAdapter.KEY_FAMILYNAME));
				phoneNumber = cursor.getString(cursor.getColumnIndex(ContactDBAdapter.KEY_PHONE));
				this.namePhones.add(id + " " + firstName + " " + familyName + "  " + phoneNumber);
			}while(cursor.moveToNext());
		}
		cursor.close();
		
		this.mDbHelper.close();
	}
			
	private void clearNamePhone() {
		this.namePhones.clear();
	}

	private void openEditContact_Activity(long cont_id){
		Intent intent = new Intent(UI_DisplayContacts.this, Andcontact1.class);
		intent.putExtra(contactID, cont_id);
		startActivityForResult(intent, SHOW_SUB_EDIT_ACTIVITY);
	}
	
}